package com.xhis.homenurse.webservice.convert;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.xhis.homenurse.models.Base_out;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by user040 on 2018/11/30.
 */

final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T>
{
    private final Gson gson;
    private final TypeAdapter<T> adapter;
    private Class<?> clazz;

    GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter, Type clazz)
    {
        this.gson = gson;
        this.adapter = adapter;
        this.clazz = (Class<?>) clazz;
    }

    @Override
    public T convert(ResponseBody value) throws IOException
    {
//         BufferedSource source = value.source();
//         source.request(Long.MAX_VALUE);
//         Buffer buffer = source.buffer();
//         Log.e("requestBody_Gson", buffer.clone().readString(Charset.forName("UTF-8")));
//
//         JsonReader jsonReader = gson.newJsonReader(value.charStream());
        try {
//             Base_out result = (Base_out) adapter.read(jsonReader);
//             Base_out result = (Base_out) adapter.read(jsonReader);
            String response = value.string();
//             if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
//                 throw new JsonIOException("JSON document was not fully consumed.");
//             }
            JSONObject jsonObject = new JSONObject(response);
            String bz = jsonObject.getString("code");
            String info = jsonObject.getString("msg");
            String data = jsonObject.getString("data");
            if (data == null)
                data = "null";
            Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
            String jsonContent = "{\"code\":\"" + bz + "\",\"msg\":\"" + info + "\"," + (TextUtils.isEmpty(data) ? "data:" : (data.startsWith("{") ? data.substring(1, data.length() - 1) : ("\"data\":\"" + data + "\""))) + "}";
            Log.e("GsonResponse", jsonContent);
            Base_out out = (Base_out) g.fromJson(jsonContent, clazz);
            out.setData(data);
            out.initData();
            return (T) out;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        } finally {
            value.close();
        }
    }
}